// ==UserScript==
// @name           phpBBv3 Show Old Posts v2
// @namespace      http://glenncarr.com/greasemonkey/phpbb
// @description    Shows posts older than 24 hours
// @include        *viewforum.php*
// $LastChangedRevision: 653 $
// $LastChangedDate: 2014-02-17 20:20:43 +0000 (Mon, 17 Feb 2014) $
// ==/UserScript==

/*
   This requires that your current phpBBv3 displayed date format (configurable in your UCP) be parseable by Date.parse()

   Updates:
   17-Mar-2008  Correctly skips cells without a date
   31-Oct-2008	Fixed some bugs; Require mm/dd at the beginning of the subject
   01-Nov-2008	Used different algo for colors
   12-Dec-2008	Fixed to work with boards that rewrite urls
   08-Dec-2012	Fixed to work with other other scripts
*/
(function(){

String.prototype.stripTags = function() {
  return this.replace(/<\/?[^>]+>|&[^;]+;|^\s+|\s+$/gi,'');
}

/*
var dbg = document.createElement( 'textarea' );
dbg.style.width = '800px';
dbg.style.height = '200px';
document.body.appendChild( dbg );
*/

var boardHome = document.evaluate( "//a[contains(@href, 'index.php')]", document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null );
if ( boardHome.snapshotLength == 0 )
    return;
boardHome = boardHome.snapshotItem( 0 ).href.replace( /\/adm\//i, '/' );

var GOOD_COLOR = GM_getValue("good_rgb_color", "#dddddd");
GM_setValue("good_rgb_color", GOOD_COLOR);

var BAD_COLOR = GM_getValue("bad_rgb_color", "#ffff33");
GM_setValue("bad_rgb_color", BAD_COLOR);

var FONT_COLOR = GM_getValue("font_rgb_color", "#000000");
GM_setValue("font_rgb_color", FONT_COLOR);

GM_xmlhttpRequest({
    method: 'GET',
    url: boardHome,
    onload: function( responseDetails )
    {
        var lastPosts = document.evaluate( "//dd[@class='lastpost']", document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null );
        if ( lastPosts.snapshotLength == 0 )
            return;

        var currDateTime = responseDetails.responseText.match( /<p>It is currently ([^<]+)</i )[ 1 ];
        var dt = new Date();
        var msCurrent = Date.parse( currDateTime );

    	var colors = ColorTransition( BAD_COLOR, GOOD_COLOR, 12 );

        for ( var iLastPost = 1; iLastPost < lastPosts.snapshotLength; iLastPost++ )
        {
            var lastPost = lastPosts.snapshotItem( iLastPost );
            var dt = lastPost.parentNode.getElementsByTagName( 'dt' )[ 0 ];
            var a = dt.getElementsByTagName( 'a' );
            if ( a.length == 0 )
            	continue;
            var subjectLink = null;
            var sold = false;
			for ( var i = 0; i < a.length; i++ )
			{
				if ( /^\s*(\*)*\s*SOLD\W+/i.test( a[ i ].innerHTML ) )
					sold = true;

				if ( /^\s*(\*)*\s*(SOLD|\d{1,2}\s*\/\s*\d{1,2})/i.test( a[ i ].innerHTML ) )
				{
					subjectLink = a[ i ];
					break;
				}
			}
			if ( subjectLink == null )
				continue;

			if ( sold )
				subjectLink.style.fontStyle = 'italic';
			else
				subjectLink.style.color = '#800000';

            var m = lastPost.innerHTML.match( /\<br\>([^<]+).*/i );
            if ( !m )
                continue;
            m = m[ 1 ];
            var msPost = Date.parse( m );
            var msDiff = msCurrent - msPost;
            var hoursDiff = msDiff / 1000 / 60 / 60;
            var hoursLeft = 24 - hoursDiff;
			var hours = Math.floor( hoursLeft );
			var min = ( '0' + Math.floor( ( hoursLeft - hours ) * 60 ) ).match( /(\d{2})$/ )[ 1 ];
			var hhmm = '(' + hours + ':' + min + ')';
			if ( sold )
			{
				subjectLink.style.backgroundColor = GOOD_COLOR;
			}
            else if ( msDiff > ( 24 * 60 * 60 * 1000 ) )
            {
            	subjectLink.innerHTML = '**SOLD** ' + subjectLink.innerHTML;
            }
            else
            {
				subjectLink.innerHTML = hhmm + ' ' + subjectLink.innerHTML;
				if ( hoursLeft < 12 )
				{
					subjectLink.style.backgroundColor = lastPost.style.backgroundColor = colors[ Math.floor( hoursLeft ) ];
				}
            }
        }
    },
    });


function ColorTransition(start, end, steps)
{
    var patterns = {};
    patterns.rgb = /^rgb\(([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\)$/i;
    patterns.hex = /^#?([0-9A-F]{2})([0-9A-F]{2})([0-9A-F]{2})$/i;
    patterns.hex3 = /^#?([0-9A-F]{1})([0-9A-F]{1})([0-9A-F]{1})$/i;

   var parseColor = function(s)
   {
      if (s.length == 3) { return s; }

      var c = patterns.hex.exec(s);
      if (c && c.length == 4)
      {
         return [ parseInt(c[1], 16), parseInt(c[2], 16), parseInt(c[3], 16) ];
      }

      c = patterns.rgb.exec(s);
      if (c && c.length == 4)
      {
         return [ parseInt(c[1], 10), parseInt(c[2], 10), parseInt(c[3], 10) ];
      }

      c = patterns.hex3.exec(s);
      if (c && c.length == 4)
      {
         return [ parseInt(c[1] + c[1], 16), parseInt(c[2] + c[2], 16), parseInt(c[3] + c[3], 16) ];
      }

      return null;
   };

   var outputColors = [];
   var startColor = currentColor = parseColor(start);
   var endColor = parseColor(end);
   var deltas = [];
   for (var rgbIndex = 0; rgbIndex < currentColor.length; rgbIndex++)
   {
      deltas[rgbIndex] = Math.abs(currentColor[rgbIndex] - endColor[rgbIndex]) / steps;
   }

   for (var step = 0; step < steps; step++)
   {
       if (step == steps -1)
       {
          currentColor = endColor;
       }

       outputColors[step] = 'rgb('+Math.floor(currentColor[0])+','+Math.floor(currentColor[1])+','+Math.floor(currentColor[2])+')';

       for (var rgbIndex = 0; rgbIndex < currentColor.length; rgbIndex++)
       {
          if ( startColor[rgbIndex] < endColor[rgbIndex] )
            currentColor[rgbIndex] += deltas[rgbIndex];
          else
            currentColor[rgbIndex] -= deltas[rgbIndex];
       }
   }

   return outputColors;
}
})();